package com.project.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImp implements IUserService{
    @Autowired
    private IUserMapper userMapper;

    @Override
    public UserBean login(String userName, String password) {
        UserBean userBean = null;
        QueryWrapper qw = new QueryWrapper();
        qw.eq("u_username",userName);
        qw.eq("u_password",password);
        List list = userMapper.selectList(qw);
        if (list.size() != 0){
            userBean = (UserBean)list.get(0);
        }
        return userBean;
    }

    @Override
    public List<UserBean> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public boolean add(UserBean user) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("u_username",user.getUserName());
        List<UserBean> list = userMapper.selectList(qw);
        if (list.size() == 0){
            userMapper.insert(user);
            return true;
        }
        return false;
    }

    @Override
    public void del(Integer userID) {
        userMapper.deleteById(userID);
    }

    @Override
    public UserBean findByID(Integer userID) {
        return userMapper.selectById(userID);
    }

    @Override
    public void updateGrade(Integer userID, String newGrade) {
        UserBean userBean = userMapper.selectById(userID);
        if (userBean != null){
            userBean.setGrade(newGrade);
            userMapper.updateById(userBean);
        }
    }

    @Override
    public void updatePassword(Integer userID, String newPassword) {
        UserBean userBean = userMapper.selectById(userID);
        if (userBean != null) {
            userBean.setPassword(newPassword);
            userMapper.updateById(userBean);
        }
    }
}
